package com.xuecheng.test.rabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer03_topic_email {
    private static final String QUEUE_INFORM_EMAIL = "queue_inform_email";
    private static final String EXCHANGE_TOPIC_INFORM="exchange_topic_inform";
    private static final String EXCHANGE_TOPIC_EMAIL="inform.#.email.#";

    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接工程
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        //设置虚拟机
        factory.setVirtualHost("/");
        //建立到代理服务器到连接
        Connection conn = factory.newConnection();
        //获得信道
        Channel channel = conn.createChannel();
        //声明交换机,1 交换机名称，2 交换机类型
        channel.exchangeDeclare(EXCHANGE_TOPIC_INFORM,BuiltinExchangeType.TOPIC);
        /**
         * 声明队列，如果Rabbit中没有此队列将自动创建
         * param1:队列名称
         * param2:是否持久化
         * param3:队列是否独占此连接 connection连接关闭则自动删除队列 若设置true可用于设置临时队列，rabbit重启则队列删除
         * param4:队列不再使用时是否自动删除此队列 与参数3一起使用用于创建临时队列
         * param5:队列参数 设置其他扩展参数
         */
       channel.queueDeclare(QUEUE_INFORM_EMAIL, true, false, false, null);

        /**
         * 参数明细
         * 1、队列名称
         * 2、交换机名称
         * 3、路由key ""代表默认
         */
        channel.queueBind(QUEUE_INFORM_EMAIL,EXCHANGE_TOPIC_INFORM,EXCHANGE_TOPIC_EMAIL);
        //定义消费方法
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            /**
             *
             */
            @Override
            public void handleDelivery(String consumerTag,
                                       Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                super.handleDelivery(consumerTag, envelope, properties, body);
                //交换机
                String exchange = envelope.getExchange();
                //路由key
                String routingKey = envelope.getRoutingKey();
                //消息id
                long deliveryTag = envelope.getDeliveryTag();
                //消息内容
                String msg = new String(body,"UTF-8");
                System.out.println("receive message.." + msg);
            }
        };

        /**
         * 监听队列String queue, boolean autoAck,Consumer callback
         * 参数明细
         * 1、队列名称
         * 2、是否自动回复，设置为true为表示消息接收到自动向mq回复接收到了，mq接收到回复会删除消息，设置为false则需要手动回复
         * 3、消费消息的方法，消费者接收到消息后调用此方法
         */
        channel.basicConsume(QUEUE_INFORM_EMAIL,true,consumer);
    }
}
